<template>
    <div>
        <van-form @submit="onSubmit">
            <van-cell-group>
                <van-cell title="头像" center size="large">
                    <template #value>
                        <van-image width="70" height="70"
                            :src="require('../../../assets/images/main_icon_head_default.png')"
                            v-if="!fromValue.avatar" />
                        <!-- <van-image width="70" height="70"
                        :src="fromValue.avatar" v-else/> -->
                        <van-uploader v-model="fileList" reupload max-count="1" :deletable="false"
                            :after-read="afterRead" :preview-size="70" ref="UploaderInstance"
                            accept="image/jpeg,image/jpg" v-else />
                        <!-- style="pointer-events: none;" -->
                    </template>
                </van-cell>
                <van-cell title="昵称" :value="fromValue.memberName" is-link size="large" @click="openDig('memberName')">
                </van-cell>
                <van-cell title="手机号码" :value="fromValue.phone" is-link size="large" @click="openDig('phone')" />
                <van-cell>
                    <template #title>
                        <div class="van-cell--large phoneTip van-cell__value van-cell--required" style="text-align: left;padding-left: 10px;">提示：手机号码仅能修改一次</div>
                    </template>
                </van-cell>
                <van-cell title="地区" :value="fromValue.area" is-link size="large" @click="openPop('area')" />
                <van-cell title="地址" :value="fromValue.address" is-link size="large" @click="openDig('address')" />
            </van-cell-group>
            <div style="width: 30%;margin: 30px auto;"><van-button type="primary" block round
                    native-type="submit">修改</van-button>
            </div>
        </van-form>

        <van-dialog v-model:show="showDig" title="请输入" show-cancel-button @confirm="submitDig"
            :beforeClose="digBeforeClose">
            <van-cell-group inset>
                <van-field v-model="digTemp.memberName" label="昵称：" v-if="digType == 'memberName'" type="text"
                    label-width="50px" />
                <van-field v-model="digTemp.phone" label="手机号码：" v-if="digType == 'phone'" type="tel"
                    label-width="80px" />
                <van-field v-model="digTemp.address" label="地址：" v-if="digType == 'address'" type="text"
                    label-width="50px" />
            </van-cell-group>
        </van-dialog>
        <van-popup v-model:show="showPop" position="bottom">
            <van-area v-model="digTemp.area" title="请选择" :area-list="areaList" v-if="popType == 'area'"
                @confirm="submitArea" @cancel="cancelArea" />
        </van-popup>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue';
import { showSuccessToast, showFailToast, showNotify, showLoadingToast, closeToast } from 'vant';
import { areaList } from '@vant/area-data';
import { queryMemberInfo, updateMemberInfo, myInfoAvatarUpdate } from "@/api/mine.js"
import { useRouter } from 'vue-router';
import * as imageConversion from 'image-conversion';
import { isBlob, blobToFile } from "@/api/utils/ruoyi.js"

const router = useRouter();
const showDig = ref(false);
const fromValue = ref({ avatar: "../../../assets/images/main_icon_head_default.png", memberName: "昵称", phone: "手机号码", area: "地区", address: "地址" })
const canDisableDig = ref(true)
const digTemp = ref({ memberName: "" })
const digType = ref(null)
const showPop = ref(false)
const popType = ref(null)
const fileList = ref([])
const savedFileList = ref([])
const { proxy } = getCurrentInstance()

onMounted(() => {
    getMemberInfo()
})

function getMemberInfo() {
    let openId = sessionStorage.getItem('token')
    queryMemberInfo(openId).then(res => {
        if (res.code == 200) {
            fromValue.value = res.data || {}
            if (fromValue.value.avatar) {
                fileList.value = [{ url: fromValue.value.avatar, isImage: true }]
                //缓存一个数据
                savedFileList.value = [{ url: fromValue.value.avatar, isImage: true }]
                console.log(fileList.value)
            }
        }
    })
}

function chooseFile() {
    console.log("点击响应")
}

async function afterRead(file) {
    showLoadingToast({
        message: '加载中...',
        forbidClick: true,
    });
    console.log(file)
    if (file) {
        //压缩图片
        await imageConversion.compress(file.file, {
            quality: 0.8,
            type: "image/jpeg",
            width: 300,
            height: 200
        }).then(res => {
            if (isBlob(res) === true) {
                file.file = blobToFile(res, file.file.name)
            } else {
                file.file = res
            }
        })
        let openId = sessionStorage.getItem('token')
        const forms = new FormData();
        forms.append("openId", openId);
        forms.append("file", file.file);
        console.log(file)
        myInfoAvatarUpdate(forms).then(res => {
            closeToast();
            if (res.code == 200) {
                setTimeout(() => {
                    fromValue.value['avatar'] = res.msg
                    showSuccessToast('上传成功');
                }, 1000)
            } else {
                setTimeout(() => {
                    fileList.value = savedFileList.value
                    showFailToast('上传失败');
                }, 1000)
            }
        }).catch((err) => {
            setTimeout(() => {
                fileList.value = savedFileList.value
                showFailToast('上传失败');
            }, 1000)
        })
    } else {
        showFailToast('上传失败');
    }

}

function openDig(type) {
    digTemp.value[type] = fromValue.value[type]
    digType.value = type
    showDig.value = true
}

function openPop(type) {
    digTemp.value[type] = fromValue.value[type]
    popType.value = type
    showPop.value = true
}

function submitDig() {
    if (digTemp.value[digType.value]) {
        fromValue.value[digType.value] = digTemp.value[digType.value]
        canDisableDig.value = true
    } else {
        showFailToast('请输入内容');
        canDisableDig.value = false
    }
}

function submitArea(obj) {
    console.log(obj)
    let tempList = []
    if (obj.selectedOptions) {
        obj.selectedOptions.map((item) => {
            tempList.push(item.text)
        })
        fromValue.value[popType.value] = tempList.join("/")
    }
    showPop.value = false
}

function cancelArea() {
    showPop.value = false
}

function digBeforeClose(action) {
    if (canDisableDig.value == false && action == 'confirm') {
        return false
    } else if (canDisableDig.value == true && action == 'confirm') {
        return true
    } else if (action == 'cancel') {
        return true
    }
}

function onSubmit() {
    let obj = {
        ...fromValue.value,
        openId: sessionStorage.getItem('token')
    }
    updateMemberInfo(obj).then(res => {
        if (res.code == 200) {
            showSuccessToast("修改成功")
            setTimeout(() => {
                router.replace("/mine")
            }, 1500);
        } else {
            showFailToast("修改失败")
        }
    })
}
</script>
<style lang="less" scoped>
.phoneTip::before{
    position: absolute;
    left: 0;
    color: var(--van-cell-required-color);
    font-size: var(--van-cell-font-size);
    content: "*";
}
.rightStyle {
    color: var(--van-cell-right-icon-color);
    display: flex;
    flex-direction: row;
    align-items: center;

    .leftStyle {
        margin-right: 5px;
        line-height: var(--van-card-desc-line-height);
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 1;
        line-break: anywhere;
        -webkit-box-orient: vertical;
    }
}

/deep/ .van-field__control {
    border: 1px solid #efefef;
}
</style>